from django.views import View
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.contrib.auth.models import User
from common.views.utils import table_api
from django.core.paginator import Paginator
from django.db.models import Q
from ..models import Dictionary

class DictListApiView(View):
    @method_decorator(login_required)
    def get(self,request):
        page = request.GET.get('page',1)
        limit = request.GET.get('limit',10)
        name = request.GET.get('name')
        code = request.GET.get('code')
        filters = [Q(parent_id=None)]
        if name:
            filters.append(Q(name__contains=name))
        if code:
            filters.append(Q(code__contains=code))
        dictionary = Paginator(Dictionary.objects.filter(*filters).order_by('id'), limit).get_page(page)
        result = [{
            'id': item.id,
            'name': item.name,
            'code': item.code,
            'enable': item.enable,
            'remark': item.remark,
            'ca_time': item.ca_time.strftime('%Y-%m-%d %H:%M:%S'),
            'up_time': item.up_time.strftime('%Y-%m-%d %H:%M:%S')
        } for item in dictionary]
        return table_api(result=result,total=dictionary.paginator.count)